package com.nuoniu.sibanyun.service.erp.in.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.erp.in.InUnit;
import com.nuoniu.sibanyun.entity.erp.in.InUnitGroup;
import com.nuoniu.sibanyun.mapper.erp.in.InUnitMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.in.IInInventoryService;
import com.nuoniu.sibanyun.service.erp.in.IInUnitGroupService;
import com.nuoniu.sibanyun.service.erp.in.IInUnitService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 计量单位 服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-09-25
 */
@Service
public class InUnitServiceImpl extends ServiceImpl<InUnitMapper, InUnit> implements IInUnitService {

    @Autowired
    private IInUnitGroupService groupService;
    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private IInInventoryService inventoryService;

    @Override
    public List<InUnit> getByGroup(Integer groupId) {
        return baseMapper.getByGroup(groupId);
    }

    @Override
    public Page<InUnit> pageList(Page pages, InUnit unit) {
        UserInfo userInfo = UserThreadLocal.get();
        InUnit unitWhere = new InUnit();
        QueryWrapper<InUnit> queryWrapper = new QueryWrapper<>(unitWhere);
        queryWrapper.eq("company_id", userInfo.getCompanyId());
        queryWrapper.eq("account_id", unit.getAccountId());

        if(unit.getUnitGroupId() != null) {
            if(unit.getUnitGroupId() == -1) {
                queryWrapper.ne("unit_group_id", 0);
            }else {
                queryWrapper.eq("unit_group_id", unit.getUnitGroupId());
            }
        }

        queryWrapper.orderByAsc("code");
        queryWrapper.orderByDesc("is_main_unit");
        Page page = page(pages, queryWrapper);
        return page;
    }

    @Override
    public String saveUnitList(List<InUnit> unitList) {
        String msg = "";
        Integer accountId = accountService.getCurrentAccountId();
        InUnitGroup group = new InUnitGroup();
        group.setName(unitList.get(0).getUnitGroupName());
        group.setAccountId(accountId);
        if (unitList.get(0).getUnitGroupId() == null) {
            if (unitList.get(0).getCode() != null) {
                group.setCode(unitList.get(0).getCode());
            }

            group.setCompanyId(UserThreadLocal.get().getCompanyId());
            groupService.save(group);
            unitList.forEach(p -> {
                p.setAccountId(accountId);
                p.setUnitGroupId(group.getId().intValue());
                p.setCompanyId(UserThreadLocal.get().getCompanyId());
            });
            this.saveBatch(unitList);
        } else {
            group.setId(unitList.get(0).getUnitGroupId().longValue());
            List<InUnit> units = new ArrayList<>();
            List<Long> unitIds = new ArrayList<>();
            InUnit mainUnit = baseMapper.getMainUnit(group.getId());
            Boolean flag = true;

            for(InUnit unit : unitList) {
                unit.setUnitGroupId(group.getId().intValue());
                if(unit.getId() != null) {
                    unitIds.add(unit.getId());
                    Integer inventoryCount = inventoryService.getByUnit(unit.getId());
                    if(inventoryCount == 0) {
                        units.add(unit);
                    }else {
                        flag = false;
                        //msg = msg.join(",", unit.getName());
                        if(unit.getIsMainUnit() && (!mainUnit.getId().equals(unit.getId()) || !unit.getName().equals(mainUnit.getName()))) {
                            throw new NuoNiuException("主计量已在物料中使用,不能更换！");
                        }
                    }
                }else {
                    unit.setAccountId(accountId);
                    unit.setCompanyId(UserThreadLocal.get().getCompanyId());
                    units.add(unit);
                }
            }

            //删除多余明细
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.notIn("id", unitIds);
            wrapper.eq("unit_group_id", group.getId());
            List<InUnit> inUnits = list(wrapper);
            for(InUnit unit : inUnits) {
                Integer inventoryCount = inventoryService.getByUnit(unit.getId());
                if(inventoryCount == 0) {
                   removeById(unit.getId());
                }
            }

            if(flag) { //更新计量单位组
                if(unitList.get(0).getCode() != null) {
                    group.setCode(unitList.get(0).getCode());
                }
                groupService.updateById(group);
            }

            this.saveOrUpdateBatch(units);
        }
        return msg;
    }

    @Override
    public InUnit getByName(String name) {
        return baseMapper.getByName(name, UserThreadLocal.get().getCompanyId());
    }

    @Override
    public void getRemoveByGroupId(Integer unitGroupId) {
        baseMapper.getRemoveByGroupId(unitGroupId);
    }

    @Override
    public void saveUnit(InUnit unit) {
        if(unit.getId() != null) {
            Integer inventoryCount = inventoryService.getByUnit(unit.getId());
            if(inventoryCount > 0) {
                throw new NuoNiuException("已在物料中使用,不能修改");
            }
        }else {
            unit.setCompanyId(UserThreadLocal.get().getCompanyId());
            unit.setAccountId(accountService.getCurrentAccountId());
        }

        saveOrUpdate(unit);
    }

    @Override
    public InUnit getByCode(String code) {
        return baseMapper.getByCode(code, UserThreadLocal.get().getCompanyId());
    }

    @Override
    public List<InUnit> listByInInventoryId(Long inInventoryId) {

        return null;
    }
}
